<template>
  <div>
<!--    面包屑导航栏-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    卡片式图区域-->
    <el-card>
<!--      提示框区域-->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        center>
      </el-alert>
<!--      选择商品级联选择器区域-->
<el-form :model="cateList">
  <el-form-item label="请选择分类:">
    <el-cascader
      collapse-tags
      expand-trigger = "hover"
      v-model="selectedKey"
      :options="cateList"
      :props="cascaderProps"
      clearable @change="handleChange" >
    </el-cascader>
  </el-form-item>
</el-form>
<!--      选择动态或静态参数区域-->
      <el-tabs v-model="activeIndex" >
        <el-tab-pane label="动态参数" name="0" @tab-click="activeDynamicType">
          <el-button type="primary" size="medium" @click="showAddParamsVisible=true" >添加参数</el-button>
          <!--      动态参数区域-->
          <el-table :data="dynamicParamsList" border stripe>
            <!-- 展开列-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                v-for="(item,i)  in scope.row.attr_vals"
                :key="i"
                closable
                type="primary"
                @close="delAttr(i,scope.row)">
                {{item}}
              </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" >
              <template slot-scope="scope">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditForm(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="delParam(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="1" @tab-click="activeStaticType">
          <el-button type="primary" size="medium" @click="showAddAttrsVisible=true" >添加属性</el-button>
          <!--      静态参数区域-->
          <el-table :data="staticParamsList" stripe border>
            <!--      展开列-->
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="params_name"></el-table-column>
            <el-table-column label="操作" >
              <el-button icon="el-icon-edit">编辑</el-button>
              <el-button icon="el-icon-delete">删除</el-button>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
<!--      显示修改对话框区域-->
        <el-dialog
          title="提示"
          :visible.sync="showEditFormVisible"
          width="50%"
          :before-close="handleClose">
          <el-form :model="editParamList" :rules="editFormRules" ref="editFormRef" label-width="70px">
            <el-form-item label="参数名" prop="attr_name">
              <el-input v-model="editParamList.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
    <el-button @click="showEditFormVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveEditParam">确 定</el-button>
  </span>
        </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      //  编辑表单绑定数据
      editForm: {},
      //  获取动态的参数列表
      dynamicParamsList: {
        attr_name: '',
        attr_vals: []
      },
      //  获取静态的参数列表
      staticParamsList: {},
      //  激活的Tab栏index
      activeIndex: '0',
      //  分类级联选择器绑定数据
      cateList: {
        cat_name: ''
      },
      //  是否显示添加动态参数对话框
      showAddParamsVisible: false,
      //  是否显示添加静态属性对话框
      showAddAttrsVisible: false,
      //  级联选择器选择的分类
      selectedKey: [],
      //  指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //  添加按钮和文本框的切换
      inputVisible: false,
      //  输入框绑定的数据
      inputValue: '',
      //  获取参数为动态还是静态
      activeType: 'many',
      //  编辑表单双向绑定的数据
      editParamList: {},
      //  是否显示编辑对话框
      showEditFormVisible: false,
      //  编辑表单校验方法
      editFormRules: {
        attr_name: [
          { required: true, message: '请填写参数名称！', trigger: blur },
          { min: 2, max: 10, message: '参数名称长度在2到10个字符', trigger: blur }
        ]
      }
    }
  },
  created () {
    this.getCateLIst()
  },
  methods: {
    //  获取分类列表用于在选择分类中使用
    async getCateLIst () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      console.log(res.data)
      this.cateList = res.data
    },
    //  处理选择的表单显示
    handleSelect () {
    },
    //  添加动态参数操作
    addParams () {
    },
    //  添加静态属性
    addAttrs () {
    },
    //  当选择父级变化时,选出父级分类的Id，查找出对应的动态参数
    async handleChange () {
      console.log(this.selectedKey)
      console.log(this.selectedKey.length)
      if (this.selectedKey.length !== 3) {
        this.selectedKey = []
      }
      const { data: res } = await this.$http.get(`categories/${this.selectedKey[2]}/attributes`, { params: { sel: this.activeType } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      this.$message.success('获取参数成功！')
      res.data.forEach(item => {
        item.attr_vals = (item.attr_vals || '').split(',')
      })
      this.dynamicParamsList = res.data
      console.log(res.data)
      // console.log(this.dynamicParamsList)
    },
    activeDynamicType() {
      this.activeType = 'many'
      this.handleChange()
    },
    activeStaticType() {
      this.activeType = 'only'
      this.handleChange()
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入完成或者失去焦点时操作
    async handleInputConfirm (row) {
      let inputValue = this.inputValue
      console.log(inputValue, row)
      if (inputValue) {
        row.attr_vals.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      this.$message.success('修改参数成功！')
      console.log(res.data)
    },
    //  展示编辑对话框
    async showEditForm(row) {
      console.log(row)
      this.showEditFormVisible = true
      const { data: res } = await this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数名称失败')
      }
      this.editParamList = res.data
      console.log(res.data)
    },
    //  保存修改参数名
    async saveEditParam() {
      const { data: res } = await this.$http.put(`categories/${this.editParamList.cat_id}/attributes/${this.editParamList.attr_id}`, {
        attr_name: this.editParamList.attr_name,
        attr_sel: 'many',
        attr_vals: this.editParamList.attr_vals
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数名失败！')
      }
      this.$message.success('修改参数名成功！')
      this.showEditFormVisible = false
      this.getCateLIst()
    },
    //  删除参数名
    async delParam(row) {
      console.log(row)
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败！')
      }
      this.$message.success('删除参数成功！')
    },
    //  删除对应的动态参数里面的值
    async delAttr (i, row) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      this.$message.success('修改参数成功！')
      console.log(res.data)
    },
    //  关闭编辑对话框的关闭处理操作
    handleClose() {
      this.$refs.editFormRef.resetFields()
      this.showEditFormVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
  .el-alert{
    margin-bottom: 20px;
  }
  .el-tag{
    margin-right: 10px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
